package com.example.test01server.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.example.test01server.config.Result;
import org.apache.tomcat.jni.File;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/files")
public class FileController {

    @Value("${server.port}")
    private String port;

    private final static String ip = "http://localhost";

    /**
     * 上传接口
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();//获取源文件的名称
        //定义文件唯一标识
        String flag = IdUtil.fastSimpleUUID();
        String filepath = System.getProperty("user.dir") + "/src/main/resources/files/" + flag + "_" + filename;
        FileUtil.writeBytes(file.getBytes(), filepath); //把文件写入到上传路径
        return Result.success(ip + ":" + port + "/files/" + flag); //返回结果 url
    }

    /**
     * 下载接口
     *
     * @param response
     * @param flag
     */
    @GetMapping("/{flag}")
    public void getFiles(HttpServletResponse response, @PathVariable String flag) {
        OutputStream os; //新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/src/main/resources/files/"; //定文件上传的根路径
        List<String> fielNames = FileUtil.listFileNames(basePath); //获取所有文件的名称
        String avatar = fielNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");//找到参数一致的文件
        try {
            if (StrUtil.isNotEmpty(avatar)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(avatar, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + avatar);//通过文件路径读取文件字节流
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (IOException e) {
            System.out.println("文件下载失败");
        }
    }
}
